package com.heima.schedule.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class RedisUtil {
    @Resource
    private  StringRedisTemplate stringRedisTemplate;


    /**
     * scan扫描keys
     * @param patten
     * @return
     */
    public  Set<String> scanKeys(String patten) {
        Set<String> keys = stringRedisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> result = new HashSet<>();
            try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
                    .match(patten).count(10000).build())) {
                while (cursor.hasNext()) {
                    result.add(new String(cursor.next()));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        });
        return keys;
    }


    /**
     * 使用pieeline执行命令，提高效率
     */
    public List<Object> refreshWithPipeline(String future_key, String topic_key, Collection<String> values){
        List<Object> objects=stringRedisTemplate.executePipelined(new RedisCallback<String>() {
            @Nullable
            @Override
            public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
                //强转为StringRedisConnection
                StringRedisConnection stringRedisConnection=(StringRedisConnection)redisConnection;
                String[] strings = values.toArray(new String[values.size()]);
                stringRedisConnection.rPush(topic_key,strings);
                stringRedisConnection.zRem(future_key,strings);
                return null;
            }
        });
        return objects;
    }
}
